using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;

namespace Test
{
    public class TestTextAutoLine : MonoBehaviour
    {
        [SerializeField] private GameObject m_Prefab;
        [SerializeField] private float m_MaxWidth = 460.0f;
        private void Awake()
        {
            CreateOneTextObj();
        }

        private void CreateOneTextObj()
        {
            string msg1 = "fsaklfjasd;lkfdjsal;fkjdsalk;fjdsklfaiu3agdfipsupdaghksjdghakjsd;fgalkghdsjklg";
            // string msg1 = "fsaklfjasd";

            GameObject textObj = GameObject.Instantiate(m_Prefab, transform, false);
            TextMeshProUGUI textMsg = textObj.transform.Find("Text").GetComponent<TextMeshProUGUI>();
            ContentSizeFitter sizeFitter = textMsg.GetComponent<ContentSizeFitter>();

            textMsg.text = msg1;

            // sizeFitter.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
            // sizeFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
            // sizeFitter.SetLayoutHorizontal();
            // sizeFitter.SetLayoutVertical();

            // Vector2 size = textMsg.GetComponent<RectTransform>().sizeDelta;
            if (textMsg.preferredWidth > m_MaxWidth)
            {
                sizeFitter.horizontalFit = ContentSizeFitter.FitMode.Unconstrained;
                textMsg.GetComponent<RectTransform>().sizeDelta = new(m_MaxWidth, 100.0f);
                sizeFitter.SetLayoutVertical();
            }
            else
            {
                sizeFitter.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
                sizeFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
                sizeFitter.SetLayoutHorizontal();
                sizeFitter.SetLayoutVertical();
            }

            Vector2 size = textMsg.GetComponent<RectTransform>().sizeDelta;
            Log.Debug(" size = ({0},{1})", size.x + 40, size.y + 40);

            textObj.GetComponent<RectTransform>().sizeDelta = new(size.x + 40, size.y + 40);

        }
    }
}